from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework import mixins
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, ListAPIView, GenericAPIView, \
    DestroyAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users.models import User, Address
from users.serializer import CreateUserSerializer, UserSerializer, EmailSerializer, VerifyEmailSerializer, \
    AddressUserSerializer, UpdataDefaultAddressSerializer

from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
from rest_framework import serializers

class TestApiView(APIView):
    def get(self,request):
        return render(request,"test.html")


class UsernameCountView(APIView):
    """
    根据用户名字检验数据库，是否存在该用户
    """
    def get(self,request, username):
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        return Response(data)

class UsercreateView(CreateAPIView):
    """
    注册新用户
    """

    serializer_class = CreateUserSerializer


class UpdataDefaultAddressView(UpdateAPIView):

    serializer_class = UpdataDefaultAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):#必须指定查询集／查询对象
        return self.request.user

    def put(self, request, *args, **kwargs):
        """
        高级子类（CreateModelMixin,GenericAPIView）
        ：CreateAPIView,DestroyAPIView,UpdateAPIView,RetrieveAPIView,ListAPIView
                条件：１　query_set=或者def get query_set()两者其一，是对象或者对象集合(many=True)
                     ２　serializer_class= 或者　def get_serializer()
                可以重写方法：def create(), def destroy(), def update(),def
        def get()获得多个对象
            return self.list(request)
        def get(pk)
            return self.retrieve(request)
        def put()
            return self.update(request)
        def post()
            return self.create(request)
        def delete()
            return self.destroy(request)

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        pk = kwargs['pk']
        # pk传参数在字典kwargs中，而不是request
        # user = self.get_object()
        # user.default_address_id=pk
        request.data['default_address_id'] = pk

        return self.update(request)


class UserDetailView(RetrieveAPIView):
    """
       查询单个用户的详情,显示个人中心的详情
    """

    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user
    # def get(self,request):
    #     return Response({"error":"为完善的个人用户视图接口"})

class BrowseHistoryView(APIView):
    def get(self,request):
        return Response({"error":"未完善的个人用户浏览历史数据视图接口"})

class UpdataEmailView(UpdateAPIView):

    serializer_class = EmailSerializer#指定专用的序列化器
    permission_classes = [IsAuthenticated]#指定权限
    # 必须先获得具体操作的当期的用户
    def get_object(self):

        return self.request.user

class VerifyEmailView(APIView):
    # def get(self, request):
    #     return Response({"error": "未完善的个人用户邮件验证回调视图接口"})

    # serializer_class = VerifyEmailSerializer  # 指定专用的序列化器
    # permission_classes = [IsAuthenticated]  # 指定权限

    # 必须先获得具体操作的当期的用户
    def get(self,request):
        token_data = request.query_params.get("token")
        if not token_data:
            return Response({'message': '缺少token'}, status=400)
        # 验证access——token有效性
        # 解密
        # tjs = TJS(settings.SECRET_KEY, 900)
        # try:
        #     data = tjs.loads(token_data.encode())
        # #     # data = tjs.loads(token_data).encode()
        # except:
        #     raise serializers.ValidationError('错误的token值')
        #
        # user_id = data.get('user_id')
        # email = data.get('email')
        # user = User.objects.get(id=user_id,email=email)
        user = User.check_verify_email_token(token_data)
        # user = User().check_verify_email_token(token_data)
        if user is None:
            return Response({'message': '链接信息无效'}, status=400)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})

class AddressUserView(mixins.DestroyModelMixin,mixins.ListModelMixin,mixins.CreateModelMixin,UpdateModelMixin,GenericAPIView):


# class AddressUserView(DestroyAPIView,ListAPIView,CreateAPIView,UpdateAPIView):
    """
    获得个人用户的收货地址
    """
    serializer_class = AddressUserSerializer
    permissions = [IsAuthenticated]

    def delete(self, request, pk):

        return self.destroy(request,pk)

    def put(self, request, pk, partial=True):

        return self.update(request, pk, partial=True)




    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def get_object(self):

        return self.request.user

    def get(self, request):
        """
        默认地址图标问题，
        １　返回的数据中一定要存在"default_address_id": user.default_address_id
        ２　该数据如何添加到已有的查询集中：主要是先将查询集转为json数据，然后将该数据添加进去
        ３　该数据添加的方式必须满足前段能够正常获得地址列表数据和该default_address_id，前段
        获得的方式为json方式，将地址列表与该值进行二次json组成，修改前段获得方式
        :param request:
        :return:
        """
        # get_object()方法根据pk参数查找queryset中的数据对象

        user=request.user

        queryset=Address.objects.all()
        # queryset[0]["default_address_id"]=user.default_address_id
        # response= JsonResponse([queryset, {"default_address_id":user.default_address_id}],safe=False)
        # response= JsonResponse(data,safe=False)
        # print(response)
        # queryset=[queryset,{"default_address_id":user.default_address_id}]

        # dep = self.get_object()
        # print(dep)
        # serializer = self.get_serializer(dep)
        # return self.list(request)
        serializer = self.get_serializer(queryset, many=True)
        data =serializer.data
        data={"default_address_id": user.default_address_id,"ls":data}
        return Response(data)



    def post(self, request):
        user = self.request.user
        request.data['user_id']=user.id

        # serializer = self.get_serializer(data=request.data)

        # serializer.is_valid(raise_exception=True)
        # self.perform_create(serializer)
        # serializer.save()

        # data = user.addresses
        # serializer = self.get_serializer(data=data)
        # headers = self.get_success_headers(serializer.data)
        # return Response(serializer.data, status=400, headers=headers)

        return self.create(request)
        # return self.create(request)
    # def get(self):
    #     return self.request.user.addresses.filter(is_deleted=False)
    # def list(self, request, *args, **kwargs):





    # def get_object(self):
    #
    #     return self.request.user



